#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
OMSP Web应用启动文件
"""

from sanic import Sanic
from sanic.response import json, text, raw, file, file_stream, empty
import sys
import os

# 将父目录添加到 Python 路径，以便能够导入 omsp 模块
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import omsp

# 创建Sanic应用
app = Sanic("OMSP")

# 注册API路由
app.route('/api/thumb', methods=['GET', 'POST'])(omsp.thumb)
app.route('/api/frm_img', methods=['GET', 'POST'])(omsp.frm_img)
app.route('/api/tasks', methods=['GET', 'POST'])(omsp.tasks)
app.route('/api/frames', methods=['GET', 'POST'])(omsp.frames)
app.route('/api/download', methods=['GET', 'POST'])(omsp.download)
app.route('/api/dld', methods=['GET', 'POST'])(omsp.dld)
app.route('/api/tasklist', methods=['GET', 'POST'])(omsp.tasklist)
app.route('/api/amag', methods=['GET', 'POST'])(omsp.amag)
app.route('/api/downf', methods=['GET', 'POST'])(omsp.downf)
app.route('/api/bindata', methods=['GET', 'POST'])(omsp.bindata)
app.route('/api/canpa', methods=['GET', 'POST'])(omsp.canpa)

# WebSocket路由
app.websocket('/ws/realtime')(omsp.realtime)
app.websocket('/ws/rt')(omsp.rt)

# 静态文件服务 - OMSP 项目专用配置
# 获取当前 omsp 目录
OMSP_DIR = os.path.dirname(os.path.abspath(__file__))
# 获取项目根目录（webs目录）
BASE_DIR = os.path.dirname(OMSP_DIR)

# OMSP 项目路由配置
app.static('/', os.path.join(OMSP_DIR, 'index.html'), name='root')  # OMSP项目首页
app.static('/static', os.path.join(BASE_DIR, 'static'), name='static_files')  # 共享静态资源
app.static('/omsp', OMSP_DIR, name='omsp_files')  # OMSP项目文件

# 为处理器注入响应类型
@app.middleware('request')
async def inject_context(request):
    request.ctx.json = json
    request.ctx.text = text
    request.ctx.raw = raw
    request.ctx.file = file
    request.ctx.file_stream = file_stream
    request.ctx.empty = empty
    request.ctx.tool = None
    request.ctx.redis = None

# CORS支持（用于跨域请求）
@app.middleware('response')
async def add_cors_headers(request, response):
    response.headers["Access-Control-Allow-Origin"] = "*"
    response.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
    response.headers["Access-Control-Allow-Headers"] = "*"

if __name__ == '__main__':
    import os
    
    # 检查是否使用测试配置
    if os.path.exists(os.path.join(BASE_DIR, 'config_test.py')):
        import sys
        sys.path.insert(0, BASE_DIR)
        from config_test import *
        host = HOST
        port = PORT
        debug = DEBUG
    else:
        # 从环境变量获取配置，或使用默认值
        host = os.environ.get('OMSP_HOST', '0.0.0.0')
        port = int(os.environ.get('OMSP_PORT', 4200))
        debug = os.environ.get('OMSP_DEBUG', 'True').lower() == 'true'  # 测试服务器默认开启调试模式
    
    print(f"""
    ============================================
    OMSP 科学探测运行操控平台
    ============================================
    服务器地址: http://{host}:{port}
    调试模式: {debug}
    工作目录: {os.getcwd()}
    
    访问地址:
    - 主页: http://{host}:{port}/
    - API: http://{host}:{port}/api/
    ============================================
    """)
    
    # 启动服务器 - 测试服务器配置
    app.run(
        host=host,
        port=port,
        debug=debug,
        access_log=True,
        auto_reload=True,  # 自动重载
        workers=1,  # 单进程模式，方便调试
        dev=True,  # 开发模式
        motd=True,  # 显示启动信息
        fast=False  # 禁用快速模式，更详细的错误信息
    ) 